package com.hq.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
public class LoginCtrl {

	@Autowired  
    private Producer captchaProducer;
	
	@RequestMapping("login")
	public String login(HttpServletRequest request) {
		return "login";

	}

	@RequestMapping("userLogin")
	@ResponseBody
	public JSONObject userLogin(HttpServletRequest request) {
		JSONObject resObject=new JSONObject();
		String msg = "";
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String captcha = request.getParameter("captcha");
		HttpSession session = request.getSession();
		String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);  
		//验证码
		boolean captchaFlag=StringUtils.isEquals(captcha, code);
		if(captchaFlag){
			
			UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
			token.setRememberMe(true);
			Subject subject = SecurityUtils.getSubject();
			try {
				subject.login(token);
				if (subject.isAuthenticated()) {
					resObject.put("res", true);
				} else {
					resObject.put("res", false);
				}
			} catch (IncorrectCredentialsException e) {
				msg = "登录密码错误. Password for account " + token.getPrincipal()
						+ " was incorrect.";
				System.out.println(msg);
				resObject.put("res", false);
				resObject.put("msg", "登录密码错误");
			} catch (ExcessiveAttemptsException e) {
				msg = "登录失败次数过多";
				System.out.println(msg);
				resObject.put("res", false);
				resObject.put("msg", "登录失败次数过多");
			} catch (LockedAccountException e) {
				msg = "帐号已被锁定. The account for username " + token.getPrincipal()
						+ " was locked.";
				System.out.println(msg);
				resObject.put("res", false);
				resObject.put("msg", "帐号已被锁定");
				
			} catch (DisabledAccountException e) {
				msg = "帐号已被禁用. The account for username " + token.getPrincipal()
						+ " was disabled.";
				System.out.println(msg);
				resObject.put("res", false);
				resObject.put("msg", "帐号已被禁用");
			} catch (ExpiredCredentialsException e) {
				msg = "帐号已过期. the account for username " + token.getPrincipal()
						+ "  was expired.";
				System.out.println(msg);
				resObject.put("res", false);
				resObject.put("msg", "帐号已过期");
			} catch (UnknownAccountException e) {
				msg = "帐号不存在. There is no user with username of "
						+ token.getPrincipal();
				System.out.println(msg);
				resObject.put("res", false);
				resObject.put("msg", "帐号不存在");
			} catch (UnauthorizedException e) {
				msg = "您没有得到相应的授权！" + e.getMessage();
				System.out.println(msg);
				resObject.put("res", false);
				resObject.put("msg", "您没有得到相应的授权");
			}
		}else{
			resObject.put("res", false);
			resObject.put("msg", "验证码错误！");
		}
		return resObject;

	}
	
	@RequestMapping("kaptcha.jpg")
	public void KaptchaServlet(HttpServletRequest request,HttpServletResponse response) throws IOException{
		HttpSession session = request.getSession();  
        String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);  
        System.out.println("******************验证码是: " + code + "******************");  
          
        response.setDateHeader("Expires", 0);  
          
        // Set standard HTTP/1.1 no-cache headers.  
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
          
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).  
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
          
        // Set standard HTTP/1.0 no-cache header.  
        response.setHeader("Pragma", "no-cache");  
          
        // return a jpeg  
        response.setContentType("image/jpeg");  
          
        // create the text for the image  
        String capText = captchaProducer.createText();  
          
        // store the text in the session  
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
          
        // create the image with the text  
        BufferedImage bi = captchaProducer.createImage(capText);  
          
        // write the data out
        ServletOutputStream out=null;
        try {  
        	 out= response.getOutputStream();  
        	ImageIO.write(bi, "jpg", out);  
            out.flush();  
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {  
            out.close();  
        }  
	}
	
	/**
	 * 登出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		SecurityUtils.getSubject().logout();
		return "login";
	}
}
